package com.kevin;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Goal which touches a timestamp file.
 *
 * @goal touch
 * @phase process-sources
 */

@Mojo(name = "generate")
public class MyMojo extends AbstractMojo {

    @Parameter(property = "tableName")
    private String tableName;
    @Parameter(property = "packageName")
    private String packageName;

    @Parameter(property = "driver")
    private String driver = "com.mysql.jdbc.Driver";
    @Parameter(property = "url")
    private String url = "jdbc:mysql://122.112.184.237:3306/sh_platform_management?characterEncoding=utf8";
    @Parameter(property = "username")
    private String username = "app_shipmgr";
    @Parameter(property = "password")
    private String password = "Sh123shipMgr!@#";


    public void execute() throws MojoExecutionException {
        System.out.println("***项目脚手架开始生成代码 生成代码位置：" + this.packageName + ".generate ****");

        packageName = packageName + "/generate";

        Configuration config = ContextUtil.getConfig("application.properties");

        if (StringUtils.isBlank(this.tableName) || StringUtils.isBlank(this.packageName)) {
            throw new RuntimeException("必须制定packageName 和 表名");
        }

        try {
            //查询表信息
            Map<String, String> table = getTableInfo(this.tableName).get(0);
            //查询列信息
            List<Map<String, String>> columns = listColumns(this.tableName);
            //生成代码
            CodeGeneratorUtil.generatorCode(table, columns, this.packageName);

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * @params: 表名
     * @return: 表信息
     * @desc: 获取表的元数据
     */
    private List<Map<String, String>> getTableInfo(String tableName) throws Exception {
        Connection conn = getConn();
        String sql = "select table_name tableName, table_comment tableComment from information_schema.tables where table_schema = (select database()) and table_name = '" + tableName + "'";
        List<Map<String, String>> result = getResult(conn, sql);
        conn.close();
        return result;
    }

    /**
     * @params: 表名
     * @return: 表列信息
     * @desc: 获取表的列信息
     */
    private List<Map<String, String>> listColumns(String tableName) throws Exception {
        Connection conn = getConn();
        String sql = "select column_name columnName, data_type dataType, column_comment columnComment, column_key columnKey, extra from information_schema.columns where table_name = '" + tableName + "' and table_schema = (select database()) order by ordinal_position";
        List<Map<String, String>> result = getResult(conn, sql);
        conn.close();
        return result;
    }


    /**
     * @params:
     * @return:
     * @desc: 数据库交互
     */
    private List<Map<String, String>> getResult(Connection conn, String sql) throws Exception {
        System.out.println(sql);
        PreparedStatement pstmt;
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int count = metaData.getColumnCount();

        List<Map<String, String>> resultList = new ArrayList<>();
        while (rs.next()) {
            Map<String, String> resultMap = new HashMap();
            //使用随机数使key不重复
            double plus = Math.random();
            int colLen = metaData.getColumnCount();
            for (int i = 1; i <= colLen; i++) {
                String columnLable = metaData
                        .getColumnLabel(i);
                String columnValue = rs.getString(i);
                resultMap.put(columnLable, columnValue);
            }
            resultList.add(resultMap);
        }
        return resultList;
    }


    /**
     * @params:
     * @return:
     * @desc: 得到一个连接
     */

    private Connection getConn() {
//        Configuration config = ContextUtil.getConfig("application.properties");
//        String driver = config.getString("driver");
//        String url = config.getString("url");
//        String username = config.getString("username");
//        String password = config.getString("password");
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}


